﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using BareWeb.FluentAzureDiagnostics;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace FluentExample.Worker
{
    public class WorkerRole : RoleEntryPoint
    {
        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.WriteLine("FluentExample.Worker entry point called", "Information");

            while (true)
            {
                Thread.Sleep(10000);
                Trace.WriteLine("Working", "Information");
            }
        }

        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            //to simulate multi-instance startup/role recycle (and marker file) delay all except first role instance
            if (!RoleEnvironment.CurrentRoleInstance.Id.EndsWith("_0"))
            {
                Thread.Sleep(5000);
            }

            var azureDiagnostics = new DiagnosticsCapture(CloudStorageAccount.DevelopmentStorageAccount);
            azureDiagnostics.Current()
                .WithLogs()
                .WhereLogsAreAbove(LogLevel.Verbose)
                .TransferLogsEvery(TimeSpan.FromMinutes(1D))
                .Commit();

            //now do similar with interfaces
            var azureDiagnostics2 =
                new DiagnosticsCapture(CloudStorageAccount.DevelopmentStorageAccount) as IDiagnosticsCapture;
            azureDiagnostics2.Default()
                .WithLogs()
                .WhereLogsAreAbove(LogLevel.Verbose)
                .TransferLogsEvery(TimeSpan.FromMinutes(1D))
                .Commit();

            return base.OnStart();
        }
    }
}
